﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Net;
using System.IO;

namespace myBoard.Framework.Web
{
    public class PageCrawler
    {
        private string _url;
        public delegate void PageSourceRetrievedHandler(string source);
        public event PageSourceRetrievedHandler PageSourceRetrieved;
        public string Url 
        {
            get { return _url; }
        }

        public string GetPageSource(string url)
        {
            return GetPageSource(url, null);
        }
        
        public string GetPageSource(string url, NetworkCredential credentials)
        {
            _url = url;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_url);
            req.Credentials = credentials;
            req.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2";
            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            TextReader tr = new StreamReader(response.GetResponseStream());
            return tr.ReadToEnd();
        }

        public void GetPageSourceAsync(string url)
        {
            GetPageSourceAsync(url, null);
        }

        public void GetPageSourceAsync(string url, NetworkCredential credentials)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) =>
                {
                    GetPageSource(url, credentials);
                };
            bw.RunWorkerCompleted += (a, b) =>
                {
                    if (b.Error != null)
                    {
                        ExceptionsManager.LogException("myBoard", b.Error, true);
                        if (PageSourceRetrieved != null)
                            PageSourceRetrieved(null);
                    }

                    if (PageSourceRetrieved != null)
                        PageSourceRetrieved(b.Result as string);
                };
            bw.RunWorkerAsync();
        }
    }
}
